import Component from 'utils/js/jquery-component';
import createClass from 'utils/js/create-class';
import wordsToEmoji from './wordsToEmoji';

function plugin($) {
  var STYLE =
    '<style>' +
    '#msgbox{position:absolute;width:100%;-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0);}' +
    '#msgbox .msg{position:relative;margin-bottom:0.3rem;padding-bottom:0.2rem;}' +
    '#msgbox .msg:after{content:"";display:block;clear:both;}' +
    '#msgbox .msg-bg{position:absolute;left:0;right:0;top:0;bottom:0;border-radius:0.2rem;background:#000;}' +
    '#msgbox .msg-l{position:relative;float:left;margin:0.2rem 0 0 0.3rem;}' +
    '#msgbox .msg-avatar{width:1.2rem;height:1.2rem;border:0.03rem solid;border-radius:50%;overflow:hidden;transform:scale(0.8);}' +
    '#msgbox .msg-avatar.man{border-color:#4FACFE;}' +
    '#msgbox .msg-avatar.woman{border-color:#FBC2EB;}' +
    '#msgbox .msg-avatar>img{width:100%;height:100%;}' +
    '#msgbox .msg-pf{pointer-events:none;position:absolute;z-index:1;width:3.26rem;height:2.24rem;top:-0.44rem;left:-0.99rem;background:center/3.2rem auto no-repeat;transform:scale(0.8);}' +
    '#msgbox .msg-pf.lv1{background-image:url(' + require('asset/title_silver1.png') + ');}' +
    '#msgbox .msg-pf.lv2{background-image:url(' + require('asset/title_silver2.png') + ');}' +
    '#msgbox .msg-pf.lv3{background-image:url(' + require('asset/title_silver3.png') + ');}' +
    '#msgbox .msg-pf.lv4{background-image:url(' + require('asset/title_gold1.png') + ');}' +
    '#msgbox .msg-pf.lv5{background-image:url(' + require('asset/title_gold2.png') + ');}' +
    '#msgbox .msg-pf.lv6{background-image:url(' + require('asset/title_gold3.png') + ');}' +
    '#msgbox .msg-pf.lv7{background-image:url(' + require('asset/title_diamond1.png') + ');}' +
    '#msgbox .msg-pf.lv8{background-image:url(' + require('asset/title_diamond2.png') + ');}' +
    '#msgbox .msg-pf.lv9{background-image:url(' + require('asset/title_diamond3.png') + ');}' +
    '#msgbox .msg-pf.lv10{background-image:url(' + require('asset/title_king1.png') + ');}' +
    '#msgbox .msg-lvmsg{text-align:center;margin-top:0.2rem;}' +
    '#msgbox .msg-r{position:relative;float:right;width:11.2rem;}' +
    '#msgbox .msg-nt{overflow:hidden;margin-top:0.2rem;}' +
    '#msgbox .msg-sex.man>.man{display:inline-block;}' +
    '#msgbox .msg-sex.woman>.woman{display:inline-block;}' +
    '#msgbox .msg-sex.man+.msg-age{background:#24CAE8;}' +
    '#msgbox .msg-sex.woman+.msg-age{background:#FF798E;}' +
    '#msgbox .msg-wim{overflow:hidden;margin-top:0.1rem;}' +
    '#msgbox .msg-wi{float:left;width:9rem;display:table;min-height:1.2rem;}' +
    '#msgbox .msg-cell{display:table-cell;vertical-align:middle;}' +
    '#msgbox .msg-imgs>img{height:1.8rem;margin:0.2rem 0.2rem 0 0;}' +
    '#msgbox .msg-mark{float:right;width:1.8rem;margin-top:0.4rem;text-align:center;}' +
    '#msgbox .msg-mark>img{width:100%;}' +
    '#msgbox .baping .msg-words{color:#FFD800;}' +
    '#msgbox .danmu .msg-mark,' +
    '#msgbox .hongbao .msg-mark,' +
    '#msgbox .diange .msg-mark{margin-top:0;}' +
    '#msgbox .hongbao .msg-words{color:red;}';
  var $style = $(STYLE).appendTo('head');

  var zoomStyle =
    '<style>' +
    '#msgbox .msg-words{font-size:0.43rem;line-height:1.5;font-weight:bold;}' +
    '#msgbox .msg-nick{font-size:0.36rem;}' +
    '#msgbox .msg-nt>div{display:inline-block;vertical-align:middle;margin-right:0.10rem;}' +
    '#msgbox .msg-nt>.msg-time{float:right;font-size:0.34rem;margin-right:0.36rem;}' +
    '#msgbox .msg-sex>img{display:none;width:0.31rem;height:0.31rem;vertical-align:middle;}' +
    '#msgbox .msg-age{font-size:0.24rem;padding:0 0.11rem;line-height:0.36rem;background:gray;}' +
    '#msgbox .msg-constel{font-size:0.24rem;padding:0 0.11rem;line-height:0.36rem;background:#4FACFE;}' +
    '#msgbox .msg-words>img{width:0.48rem;height:0.48rem;vertical-align:middle;}' +
    '#msgbox .givegift .msg-wim,' +
    '#msgbox .givereward .msg-wim{overflow:visible;}' +
    '#msgbox .givegift .msg-cell,' +
    '#msgbox .givereward .msg-cell{display:block;}' +
    '#msgbox .givegift .msg-words,' +
    '#msgbox .givereward .msg-words{white-space:nowrap;height:1.2rem;line-height:1.1rem;}' +
    '#msgbox .givegift .msg-words>span,' +
    '#msgbox .givereward .msg-words>span{display:inline-block;vertical-align:middle;height:100%;}' +
    '#msgbox .givegift .msg-words .name,' +
    '#msgbox .givereward .msg-words .name{color:#FFF600;}' +
    '#msgbox .givegift .msg-words .nick,' +
    '#msgbox .givereward .msg-words .nick{color:#FFF600;max-width:4rem;overflow:hidden;text-overflow:ellipsis;}' +
    '#msgbox .givegift .msg-words>.gift>img,' +
    '#msgbox .givereward .msg-words>.gift>img{width:2rem;height:2rem;margin-top:-0.6rem;}' +
    '#msgbox .givegift .msg-imgs,' +
    '#msgbox .givereward .msg-imgs{display:none;}' +
    '</style>';
  var $zoomStyle = $(zoomStyle).appendTo('head');
  var zoomStyleText = $zoomStyle.text();

  var bgOpacityStyle = '<style></style>';
  var $bgOpacityStyle = $(bgOpacityStyle).appendTo('head');
  var bgOpacityStyleText = $bgOpacityStyle.text();

  var cns = ['', ' baping', ' danmu', ' hongbao', ' zuojia', ' hongbao', ' hongbao', '', ' hongbao', '', ' givegift', ' givegift', ' givereward', ' diange'];
  var baThemeImgs = {
    '吃鸡霸屏': 'baping_chiji.png',
    '生日霸屏': 'baping_birthday.png',
    '示爱霸屏': 'baping_love.png',
    '缘分霸屏': 'baping_peach.png',
    '求约霸屏': 'baping_date.png',
    '相爱霸屏': 'baping_heart.png',/*
    '平安夜霸屏': 'baping_christmaseve.png',
    '春节霸屏': 'baping_spring.png',
    '情人霸屏': 'baping_valentine.png',
    '元宵霸屏': 'baping_lantern.png',
    '世界杯霸屏': 'baping_worldcup.png',
    '七夕节霸屏': 'baping_qixijie.png',
    '520霸屏': 'baping_wuerling.png',
    '儿童节霸屏': 'baping_children.png',
    '中秋节霸屏': 'baping_zhongqiu.png',
    '长假霸屏': 'baping_changjia.png',
    '万圣节霸屏': 'baping_hallowmas.png',
    '圣诞霸屏': 'baping_christmas.png',
    '元旦霸屏': 'baping_newyear.png', */
    '新春霸屏': 'baping_spring.png',
  };

  $.fn.msgSlider = function (opt) {
    var defaults = {
      displayMode: 'realtime', // 显示模式(carousel:轮播显示, realtime:实时显示)
      delay: 4000, // 轮播模式下，多长时间执行一次滚动
      max: 20, // 最多显示多少条消息
      initData: [], // 初始加载数据，必须是数组
      makeDomStr: function (data) { // 根据data拼接DOM字符串，data必须是数组
        for (var i = 0, str = ''; i < data.length; i++) {
          var d = data[i];

          // 数据二次处理
          var words = wordsToEmoji(d.words); // 将代表表情的字符串转化为表情
          var imgs = '';
          var msgMark = '';
          var sexClass = ['', 'man', 'woman'][d.sex];
          var avatar = d.avatar || require('asset/test.jpg');
          var lv = 10;
          var lvMsgs = ['', '白银1级', '白银2级', '白银3级', '黄金4级', '黄金5级', '黄金6级', '钻石7级', '钻石8级', '钻石9级', '王者10级'];

          // 拼接
          str +=
            '<div class="msg" mid=' + d.id + '>' +
            '<div class="msg-bg"></div>' +
            '<div class="msg-l">' +
            '<div class="msg-avatar ' + sexClass + '"><img src=' + avatar + '></div>' +
            '<div class="msg-pf lv' + lv + '"></div>' +
            '<div class="msg-lvmsg">' + lvMsgs[lv] + '</div>' +
            '</div>' +
            '<div class="msg-r">' +
            '<div class="msg-nt">' +
            '<div class="msg-nick">' + d.nick + '</div>' +
            '<div class="msg-sex ' + sexClass + '">' +
            '<img class="man" src="' + require('asset/man_pc.png') + '">' +
            '<img class="woman" src="' + require('asset/woman_pc.png') + '">' +
            '</div>' +
            '<div class="msg-age">' + (d.age ? d.age + '岁' : '') + '</div>' +
            '<div class="msg-constel">' + (d.constel ? d.constel : '巨蟹座') + '</div>' +
            '<div class="msg-time">' + d.time + '</div>' +
            '</div>' +
            '<div class="msg-wim">' +
            '<div class="msg-wi">' +
            '<div class="msg-cell">' +
            (words ? '<div class="msg-words">' + words + '</div>' : '') +
            (imgs ? '<div class="msg-imgs">' + imgs + '</div>' : '') +
            '</div>' +
            '</div>' +
            msgMark +
            '</div>' +
            '</div>' +
            '</div>';
        }
        return str;
      },
      avatarOSS: '?x-oss-process=image/resize,m_fill,h_120,w_120',
      msgImgOSS: '?x-oss-process=image/resize,h_180'
    };
    opt = $.extend({}, defaults, opt);

    var $box = this;
    var $boxParent = $box.parent();
    var moving = false; // 是否正在滚动
    var playing = false; // 是否正在play循环
    var mid = 0; // 自动mid, 若数据中没有mid时，自动添加mid
    var mids = []; // 当前数据中所有的mid
    var timer; // 轮播定时器ID
    var movingTimer; // 过渡动画在moving时的定时器
    var $toBeRemoved; // 轮播中带删除的被clone的jquery对象
    var _skin;


    var stop = function () { // 在进行插入、删除等操作前，将正在moving的过渡动画直接过渡到结束
      if (!moving) return;
      clearTimeout(movingTimer);
      $toBeRemoved && $toBeRemoved.remove(), $toBeRemoved = null;
      $box.css({ transition: '' });
      moving = false;
    }
    var play = function () { // 播放
      if (playing) return;
      playing = true;
      switch (opt.displayMode) {
        case 'carousel':
          var carousel = function () {
            timer = setTimeout(carousel, opt.delay);
            if (moving) return;
            if ($box.height() < $boxParent.height()) return;
            var $children = $box.children();
            $toBeRemoved = $children.eq(0);
            $box.append($toBeRemoved.clone());
            $box.css({ transition: 'transform 0.5s', transform: 'translate3d(0,-' + $children[1].offsetTop + 'px,0)' });
            moving = true;
            movingTimer = setTimeout(function () {
              moving = false;
              $toBeRemoved.remove();
              $toBeRemoved = null;
              $box.css({ transition: '', transform: 'translate3d(0,0,0)' });
            }, 500);
          };
          carousel();
          break;
        case 'realtime':
          $box.css({ transition: 'transform 0.5s', transform: 'translate3d(0,-' + ($box.height() - $boxParent.height()) + 'px,0)' });
          moving = true;
          movingTimer = setTimeout(function () {
            moving = false;
          }, 500);
          break;
      }
    };
    var pause = function () { // 暂停
      if (!playing) return;
      clearTimeout(timer);
      playing = false;
    };
    var insert = function (data, cb) { // 在最新的消息后面插入一条消息
      data.id = data.id || mid++;
      stop();
      var maxMid = mids[mids.length - 1];
      if (maxMid) {
        $box.find('[mid=' + maxMid + ']').last().after(opt.makeDomStr([data]));
      } else {
        $box.append(opt.makeDomStr([data]));
      }
      mids.push(data.id * 1);
      if (mids.length > opt.max) $toBeRemoved = $box.find('[mid=' + mids.shift() + ']').first();
      switch (opt.displayMode) {
        case 'carousel':
          $toBeRemoved && $toBeRemoved.remove(), $toBeRemoved = null;
          cb && cb();
          break;
        case 'realtime':
          var tranY = $boxParent.height() - $box.height();
          tranY > 0 && (tranY = 0);
          $box.css({ transition: 'transform 0.5s', transform: 'translate3d(0,' + tranY + 'px,0)' });
          moving = true;
          movingTimer = setTimeout(function () {
            moving = false;
            if ($toBeRemoved) {
              $toBeRemoved.remove();
              $toBeRemoved = null;
              var tranY = $boxParent.height() - $box.height();
              tranY > 0 && (tranY = 0);
              $box.css({ transition: '', transform: 'translate3d(0,' + tranY + 'px,0)' });
            }
            cb && cb();
          }, 500);
          break;
      }
    };
    var remove = function (mid) { // 删除一条消息
      var idx = mids.indexOf(mid * 1);
      if (idx == -1) return;
      stop();
      mids.splice(idx, 1);
      $box.find('[mid=' + mid + ']').remove();
      switch (opt.displayMode) {
        case 'carousel':
          break;
        case 'realtime':
          var tranY = $boxParent.height() - $box.height();
          tranY > 0 && (tranY = 0);
          $box.css({ transition: 'transform 0.5s', transform: 'translate3d(0,' + tranY + 'px,0)' });
          moving = true;
          movingTimer = setTimeout(function () {
            moving = false;
          }, 500);
          break;
      }
    };
    var setDisplayMode = function (mode) { // 设置显示模式
      if (opt.displayMode == mode) return;
      pause();
      stop();
      opt.displayMode = mode;
      switch (mode) {
        case 'carousel':
          break;
        case 'realtime':
          $box.html($box.children().get().sort(function (a, b) {
            return $(a).attr('mid') - $(b).attr('mid');
          }));
          break;
      }
      setTimeout(play, 200); // 使用定时器延迟的目的是为了保证充分渲染之后，计算出准确的容器高度
    };
    var zoomFontSize = function (num) { // 按照给定的倍数缩放文字大小
      pause();
      $zoomStyle.html(zoomStyleText.replace(/(\d+|\d*\.\d+)(?=rem)/g, function (k) { return (k * num).toFixed(2) }));
      play();
    };
    var setBgOpacity = function (opacity) { // 调整文字框背景不透明度
      $bgOpacityStyle.html('#msgbox .msg-bg{opacity:' + opacity / 100 + ';}');
    };
    var setSkin = function (skin) {
      $box.removeClass(_skin).addClass(_skin = skin);
    };


    var init = function () { // 初始化
      var data = opt.initData.slice(-opt.max);
      data.forEach(function (d) {
        mids.push(d.id = d.id * 1 || mid++);
      });
      $box.html(opt.makeDomStr(data));
      play();
      $(window).resize(function () {
        pause();
        play();
      });
    };

    // 入口
    init();
    return { play: play, pause: pause, insert: insert, remove: remove, setDisplayMode: setDisplayMode, zoomFontSize: zoomFontSize, setSkin: setSkin, setBgOpacity: setBgOpacity };
  };
}

export default createClass(Component, {
  __name__: 'MsgSlider',

  __init__: function (el, initData) {
    this.use(plugin);
    var msgSlider = this.$(el).msgSlider({ initData: initData || [] });
    Object.assign(this, msgSlider);
  },
});
